# 学生成绩管理系统
import os.path
import sys

students = []

def Menu():
    print("1. 新增学生")
    print("2. 显示学生")
    print("3. 查找学生")
    print("4. 删除学生")
    print("0. 退出")
    choice = input("选择->")
    return choice

def insert():
    print("开始新增学生...")
    studentId = input("输入学号: ")
    name = input("输入姓名: ")
    gender = input("输入性别: ")
    if gender not in ('男', '女'):
        print("性别输入错误，请重新输入！")
        return
    classId = input("输入班级: ")
    student = {
        'studentId': studentId,
        'name': name,
        'gender': gender,
        'classId': classId
    }
    global students
    students.append(student)
    save()
    print("新增学生结束...")

def show():
    print("显示学生开始...")
    for s in students:
        print(f"[{s['studentId']}], 姓名: {s['name']}, 性别: {s['gender']}, 班级: {s['classId']}")
    print("显示学生结束...")

def find():
    print("查找学生开始...")
    findName = input("输入要查找学生的名字: ")
    count = 0
    for s in students:
        if findName == s['name']:
            print(f"[{s['studentId']}], 姓名: {s['name']}, 性别: {s['gender']}, 班级: {s['classId']}")
            count += 1
    print(f"查找学生结束... 一共查找到了{count}个学生")

def delete():
    print("删除学生开始...")
    studentId = input("输入要删除学生的学号: ")
    for s in students:
        if studentId == s['studentId']:
            print(f"删除学号为{studentId}的学生成功!")
            students.remove(s)
    save()
    print("删除学生结束...")

def save():
    with open('record.txt', 'w', encoding='utf8') as f:
        for s in students:
            f.write(f"{s['studentId']}\t{s['name']}\t{s['gender']}\t{s['classId']}\n")
    print(f"保存成功, 保存了{len(students)}个数据")

def load():
    if not os.path.exists('record.txt'):
        return
    global students
    students = []
    with open('record.txt', 'r', encoding='utf8') as f:
        for line in f:
            # 清除空格符：空格，\n,\t
            line = line.strip()
            tokes = line.split('\t')
            if len(tokes) != 4:
                print("文件格式错误!")
                return
            student = {
                'studentId': tokes[0],
                'name': tokes[1],
                'gender': tokes[2],
                'classId': tokes[3]
            }
            students.append(student)
        print(f"读取文件成功，读取了{len(students)}个数据")

def Main():
    print("----------------------------------")
    print("        欢迎来到学生成绩管理系统      ")
    print("----------------------------------")
    load()
    while True:
        choice = Menu()
        if choice == '1':
            insert()
        elif choice == '2':
            show()
        elif choice == '3':
            find()
        elif choice == '4':
            delete()
        elif choice == '0':
            print("退出...")
            sys.exit(0)
        else:
            print("输入错误，请重新输入！")
            continue


Main()
